<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/8
 * Time: 13:25
 */
namespace App\Service\Api;

use App\Http\Model\Mysql\ApplyWithdraw;
use App\Http\Model\Mysql\CouponModel;
use App\Http\Model\Mysql\OrderIncomeModel;
use App\Http\Model\Mysql\OrderModel;
use App\Http\Model\Mysql\UploadLogModel;
use App\Http\Model\Mysql\UserBindModel;
use App\Http\Model\Mysql\UserModel;
use App\Http\Model\Mysql\UserCouponModel;
use App\Utils\UploadAliOss;
use App\Utils\WechatUtil;
use Carbon\Carbon;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\URL;

class UserService extends BaseService
{
    /**
     * 保存用户的个人数据
     * @param string $decrypted_data
     * @param string $iv
     * @return array
     */
    public function userInfo(string $decrypted_data, string $iv)
    {
        $user_info      =   request()->post('api_user');
        $user_id        =   $user_info['user_id'];
        //解析返回的数据
        $session_key    =   UserModel::where(['uid' => $user_id])->value('session_key');
        [$error_code, $result]  =   WechatUtil::decryptData($session_key, $decrypted_data, $iv);

        if ($error_code == WechatUtil::DECRYPT_OK) {
            UserModel::where(['uid' => $user_id])->update([
                'nickname'  =>  $result['nickName'],
                'country'   =>  $result['country'],
                'province'  =>  $result['province'],
                'city'      =>  $result['city'],
                'headimg'   =>  $result['avatarUrl'],
                'language'  =>  $result['language']
            ]);
            return [true, "更新成功"];
        } else {
            return [false, $result];
        }
    }

    /**
     * 获取用户领取的优惠券列表
     * @param int $is_active
     * @return array
     */
    public function userCoupon(int $is_active)
    {
        $user_info  =   request()->post('api_user');
        $user_id    =   $user_info['user_id'];
        $model      =   UserCouponModel::query()->with([
                            'coupon' => function ($query) {
                                $query->select(['id', 'name', 'desc', 'min_price', 'sub_price', 'type', 'discount']);
                            }
                        ])->where('user_id', '=', $user_id)->where('is_delete', '=', UserCouponModel::NOT_DELETE);

        if ($is_active == 1) {
            $model->where('is_use', '=', UserCouponModel::NOT_USE)->where('end_time', '>=', Carbon::now()->timestamp);
        } else {
            $model->where(function ($query) {
                $query->where('is_use', '=', UserCouponModel::IS_USE)->orWhere('end_time', '<', Carbon::now()->timestamp);
            });
        }

        $list   =   $model->select(['id', 'user_id', 'coupon_id', 'fetch_time', 'begin_time', 'end_time', 'is_use'])->get()->each(function (&$item) {
            $item->expire_desc  =   Carbon::now()->timestamp > $item->end_time ? '已失效' : '未失效';
            $item->fetch_time   =   Carbon::createFromTimestamp($item->fetch_time)->toDateTimeString();
            $item->begin_time   =   Carbon::createFromTimestamp($item->begin_time)->toDateTimeString();
            $item->end_time     =   Carbon::createFromTimestamp($item->end_time)->toDateTimeString();
            $item->use_desc     =   $item->is_use == UserCouponModel::IS_USE ? '已使用' : '未使用';
        });
        return [true, $list->isEmpty() ? [] : $list->toArray()];
    }

    /**
     * 用户中心页面数据显示
     * @return array
     */
    public function userCenter()
    {
        $user_info  =   request()->post('api_user');
        $user_id    =   $user_info['user_id'];

        //佣金统计
        $total_income   =   OrderIncomeModel::where(['uid' => $user_id, 'status' => OrderIncomeModel::STATUS_DEAL])->select([DB::raw('sum(income) as income'), 'reward'])->groupBy('reward')->get();

        //累积邀请奖励
        $total_invite   =   $total_promote   =   0;
        foreach ($total_income as $item) {
            if ($item['reward'] == OrderIncomeModel::REWARD_PROMOTE) {
                $total_promote  +=  $item['income'];
            }

            if ($item['reward'] == OrderIncomeModel::REWARD_INVITE) {
                $total_invite   +=  $item['income'];
            }
        }

        $total_reward   =   $total_invite + $total_promote;

        //提现
        $total_apply    =   ApplyWithdraw::where(['user_id' => $user_id, 'status' => ApplyWithdraw::APPLY_ALREADY])->sum('pay_amount');

        //当日佣金
        $total_daily    =   OrderIncomeModel::where(['uid' => $user_id, ['day_time', '>', Carbon::now()->format('Y-m-d')]])->sum('income');

        //当月佣金
        $total_month    =   OrderIncomeModel::where(['uid' => $user_id, ['day_time', '>', Carbon::now()->format('Y-m-01')]])->sum('income');

        //临时客户
        $total_client   =   UserBindModel::where(['share_user' => $user_id, 'bind_type' => UserBindModel::BIND_WEAK, ['expire_time', '>', Carbon::now()->timestamp]])->count();

        //累积邀请人
        $total_share    =   UserBindModel::where(['share_user' => $user_id])->count();

        //累积销售订单
        $total_order    =   OrderModel::where(['user_id' => $user_id, 'is_pay' => OrderModel::IS_PAY, 'order_status' => OrderModel::IS_NORMAL])->count();

        return [true, [
            'total_reward'  =>  $total_reward,
            'total_invite'  =>  $total_invite,
            'total_promote' =>  $total_promote,
            'total_apply'   =>  $total_apply,
            'total_daily'   =>  $total_daily,
            'total_month'   =>  $total_month,
            'total_client'  =>  $total_client,
            'total_share'   =>  $total_share,
            'total_order'   =>  $total_order,
        ]];
    }

    /**
     * 用户上传文件
     * @param UploadedFile $file
     * @return array
     */
    public function userUpload(UploadedFile $file)
    {
        $user_info      =   request()->post('api_user');
        $user_id        =   $user_info['user_id'];
        $setting_path   =   Config::get('upload.local_path');
        $upload_path    =   public_path($setting_path);
        $extension      =   $file->extension();
        $name           =   $file->getFilename();
        $file_name      =   sha1($file->getClientOriginalName() . createRandomNumber()) . '.' . $extension;
        $file_type      =   $file->getType();
        $file_size      =   $file->getSize();
        try {
            $file->move($upload_path, $file_name);
            $move_name      =   $upload_path . DIRECTORY_SEPARATOR . $file_name;
            $upload_util    =   new UploadAliOss();
            [$flag, $result]=   $upload_util->uploadFile([$name => $move_name]);
            $flag ? @unlink($move_name) : NULL;
            $move_name      =   $flag ? $result[$name] : URL::asset($setting_path . '/' . $file_name);
            $file_unique    =   createUniqueID();

            UploadLogModel::create([
                'file_unique'=> $file_unique,
                'file_url'  =>  $move_name,
                'extension' =>  $extension,
                'file_type' =>  $file_type,
                'file_size' =>  $file_size,
                'upload_user'=> $user_id,
                'is_admin'  =>  0
            ]);
            return [true, [
                'url'       =>  $move_name,
                'extension' =>  $extension,
                'file_unique'=> $file_unique
            ]];
        } catch (\Exception $e) {
            return [false, $e->getMessage()];
        }
    }

    /**
     * 查看用户信息
     * @return array
     */
    public function userMember()
    {
        $user_info      =   request()->post('api_user');
        $user_id        =   $user_info['user_id'];
        //查看用户数据
        $user_detail    =   UserModel::where(['uid' => $user_id])->select(['uid', 'unique_id', 's_uid', 't_uid', 'nickname', 'openid', 'relname', 'phone', 'balance', 'total_balance', 'level', 'recommend', 'headimg', 'birthday', 'gender'])->first();

        if (empty($user_detail)) {
            return [false, '用户信息不存在'];
        }

        return [true, $user_detail->toArray()];
    }

    /**
     * 用户海报分享
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function userPoster()
    {
        $user_info  =   request()->post('api_user');
        [$flag, $result]    =   WechatUtil::getUnlimitedCode(['scene' => 'poster'], $user_info['user_id']);    //, 'page' => '/pages/generalize/index?user_id=' . $user_info['unique_id']
        if ($flag && isset($result['img_path'])) {
            return [true, [
                'user_info' =>  $user_info,
                'code_img'  =>  $result['img_path'],
            ]];
        } else {
            return [false, '二维码生成失败'];
        }
    }

    /**
     * 用户头像修改
     * @param UploadedFile $file
     * @return array
     */
    public function userAvatar(UploadedFile $file)
    {
        [$flag, $result]    =   $this->userUpload($file);
        if (!$flag) {
            return [false, '用户头像上传错误'];
        }

        $user_info  =   request()->post('api_user');
        $user_avatar=   UserModel::where(['uid' => $user_info['user_id']])->update(['headimg'   =>  $result['url']]);
        if ($user_avatar) {
            return [true, ['headimg' => $result['url']]];
        } else {
            return [false, '用户头像修改错误'];
        }
    }

    /**
     * 用户修改个人 资料
     * @param array $params
     * @return array
     */
    public function userBasic(array $params)
    {
        $user_info  =   request()->post('api_user');
        $update     =   [];
        if (!empty($params['nickname'])) {
            $update['nickname'] =   trim($params['nickname']);
        }

        if (!empty($params['phone'])) {
            $update['phone']    =   trim($params['phone']);
        }

        if (isset($params['gender'])) {
            $update['gender']   =   $params['gender'];
        }

        if (!empty($params['birthday'])) {
            $update['birthday'] =   Carbon::parse($params['birthday'])->toDateString();
        }

        if (empty($update)) {
            return [false, '用户资料不能为空'];
        }

        $user_basic =   UserModel::where(['uid' => $user_info['user_id']])->update($update);
        if ($user_basic) {
            return [true, '修改成功'];
        } else {
            return [false, '修改失败'];
        }
    }

}
